import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
import Layout from '@/layout/index.vue'
import Center from '@/layout/center/center.vue'
import {getRoutersApi} from '@/api/menu/index.ts'
import {RouteRecordRaw} from "vue-router";
import {imageEmits} from "element-plus";
// 获取views下面的所有.vue文件
//@ts-ignore
const modules = import.meta.glob('../../../views/**/*.vue')

export const useMenuStore = defineStore('menuStore', () => {
    // 菜单是否折叠
    const collapse = ref(false)
    // 菜单数据
    const menuList = ref([
        {
            path: "/",
            component: () => import("@/layout/index.vue"),
            name: "dashboard",
            meta: {
                title: "首页",
                icon: "HomeFilled",
                role: ['sys:dashboard']
            }
        }
    ])

    // 计算属性，返回当前的折叠状态
    const getCollapse = computed(() => collapse.value)
    // 计算属性，返回当前的菜单列表
    const getListMenu = computed(() => menuList.value)
    // 切换折叠状态的方法
    const toggleCollapse = () => {
        collapse.value = !collapse.value
    }

    // 获取菜单数据
    const getMenuList = (router: any) => {
        return new Promise((resolve, reject) => {
            getRoutersApi().then((res: any) => {
                // 生成路由
                let accessRoute = generateRoute(res.data, router) as any
                menuList.value = menuList.value.concat(accessRoute)
                console.log(menuList.value)
                resolve(menuList)
            }).catch((error) => {
                reject(error)
            })
        })
    }

    return {getCollapse, collapse,menuList, toggleCollapse,getMenuList,getListMenu}
})

export function generateRoute(routes: RouteRecordRaw[], router: any) {
    // 路由数据
    const res: Array<RouteRecordRaw> = [];
    routes.forEach((route: any) => {
        console.log(route)
        const temp = {...route}
        const component = route.component
        // 生成路由的component
        if (route.component) {
            if (component == 'Layout') {
                temp.component = Layout
            } else {
                temp.component = modules[`../../../${component}`]
            }
        }
        // 有下级  (三级路由)
        if (temp.children && temp.children.length > 0) {
            if (route.component != 'Layout') {
                temp.component = Center
            }
            // 递归调用
            temp.children = generateRoute(temp.children, router)
        }
        res.push(temp)
        // 加入路由
        router.addRoute(temp)
    })
    return res;
}
